package com.vm.osm.business.controller;

import com.vm.osm.business.common.Constants;
import com.vm.osm.business.common.ControllerExceptionHandler;
import com.vm.osm.business.common.ValidLogon;
import com.vm.osm.business.common.exception.BusinessException;
import com.vm.osm.business.dto.eam.equ.EquCommonAttr;
import com.vm.osm.business.dto.eam.equ.EquDiyAttr;
import com.vm.osm.business.dto.eam.equ.GetCommonAttrReq;
import com.vm.osm.business.dto.eam.equ.GetDiyAttrReq;
import com.vm.osm.business.dto.eam.equ_part.SearchEamEquPartReq;
import com.vm.osm.business.dto.eam.equ_part_type.EquPartTypeTree;
import com.vm.osm.business.dto.eam.equ_type.EquTypeTree;
import com.vm.osm.business.dto.eam.manufactor.Manufactor;
import com.vm.osm.business.dto.eam.measure_unit.MeasureUnit;
import com.vm.osm.business.dto.eam.project.ProjectPageReq;
import com.vm.osm.business.dto.eam.project.ProjectPageRsp;
import com.vm.osm.business.dto.eam.project.ProjectRow;
import com.vm.osm.business.dto.eam.supplier.Supplier;
import com.vm.osm.business.dto.req.logic_equ.*;
import com.vm.osm.business.dto.rsp.asset_equ.AssetEquDetail;
import com.vm.osm.business.dto.rsp.asset_equ.PageAssetEquRsp;
import com.vm.osm.business.dto.rsp.logic_equ.*;
import com.vm.osm.business.entity.OsmLogicEqu;
import com.vm.osm.business.service.IAssetEquService;
import com.vm.osm.business.service.IOsmLogicEquService;
import com.vm.osm.business.service.eam.*;
import com.vm.osm.business.util.UserDataUtil;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Arrays;

/**
 * 逻辑设备信息
 *
 * @author Xuerong Xue
 */
@RestController
@RequestMapping("/v1.0")
@Api(value = "OsmLogicEquController", description = "逻辑设备信息", tags = {"OsmLogicEquController"})
public class OsmLogicEquController extends ControllerExceptionHandler {
    private Logger LOG = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private IOsmLogicEquService osmLogicEquService;
    @Autowired
    private IEamEquTypeService eamEquTypeService;
    @Autowired
    private IEamEquService eamEquInfoService;
    @Autowired
    private IEamEquPartTypeService eamEquPartTypeService;
    @Autowired
    private IEamEquPartService eamEquPartInfoService;
    @Autowired
    private IAssetEquService eamAssetEquService;
    @Autowired
    private IEamMeasureUnitService eamMeasureUnitService;
    @Autowired
    private IEamSupplierService eamSupplierService;
    @Autowired
    private IEamManufactorService eamManufactorService;
    @Autowired
    private IEamProjectService eamProjectService;

    /**
     * 分页查询
     */
    @GetMapping(value = "/logic_equs")
    @ValidLogon
    @ApiOperation(value = "分页查询", response = LogicEquPageRsp.class)
    @ApiImplicitParam(name = "session_id", value = "访问令牌", required = true, dataType = "string", paramType = "header")
    public Object page(@Valid @ModelAttribute LogicEquPageReq request, BindingResult valid) {
        LOG.info("【逻辑设备】（分页查询） -> 请求参数：{}", request);
        if (valid.hasErrors()) {
            throw new BusinessException(valid.getFieldError().getDefaultMessage());
        }
        return osmLogicEquService.page(request);
    }

    /**
     * 获取设备详情
     */
    @GetMapping(value = "/logic_equ/{id}")
    @ValidLogon
    @ApiOperation(value = "获取设备详情", response = GetLogicEquDetailRsp.class)
    @ApiImplicitParam(name = "session_id", value = "访问令牌", required = true, dataType = "string", paramType = "header")
    public Object detail(@ApiParam(required = true, name = "id", value = "设备Id") @PathVariable String id) {
        LOG.info("【逻辑设备】（获取设备详情） -> 设备Id：{}", id);
        return osmLogicEquService.detail(id);
    }

    /**
     * 删除设备
     */
    @DeleteMapping(value = "/logic_equ/{ids}")
    @ValidLogon
    @ApiOperation(value = "删除")
    @ApiImplicitParam(name = "session_id", value = "访问令牌", required = true, dataType = "string", paramType = "header")
    public void delete(@ApiParam(required = true, name = "ids", value = "设备Id列表") @PathVariable String[] ids) {
        LOG.info("【逻辑设备】（删除设备） -> 设备Id列表：{}", Arrays.asList(ids));
        osmLogicEquService.batchDelete(Arrays.asList(ids));
    }

    /**
     * 设备所属候选
     */
    @GetMapping(value = "/logic_equ/belonger/candidate")
    @ValidLogon
    @ApiOperation(value = "设备所属候选", response = LogicEquBelonger[].class)
    @ApiImplicitParam(name = "session_id", value = "访问令牌", required = true, dataType = "string", paramType = "header")
    public Object candidate(HttpServletRequest servlet) {
        String enterpriseId = UserDataUtil.getUserSelectedEnterpriseId(servlet);
        LOG.info("【逻辑设备】（设备所属候选） -> 企业Id：{}", enterpriseId);
        return osmLogicEquService.candidate(enterpriseId);
    }

    /**
     * 获取设备类型树
     */
    @GetMapping("/logic_equ/type/tree")
    @ValidLogon
    @ApiOperation(value = "获取设备类型树", response = EquTypeTree[].class)
    @ApiImplicitParam(name = "session_id", value = "访问令牌", required = true, dataType = "string", paramType = "header")
    public Object getLogicEquTypeTree(HttpServletRequest servlet) {
        String sessionId = servlet.getHeader(Constants.SESSION_ID);
        LOG.info("【逻辑设备】（获取设备类型树） -> 登录令牌：{}", sessionId);
        return eamEquTypeService.getBySessionId(sessionId);
    }

    /**
     * 获取企业设备类型树
     */
    @GetMapping("/logic_equ/part_type/tree")
    @ValidLogon
    @ApiOperation(value = "获取设备配件类型树", response = EquPartTypeTree[].class)
    @ApiImplicitParam(name = "session_id", value = "访问令牌", required = true, dataType = "string", paramType = "header")
    public Object getEquPartTypeTree(HttpServletRequest servlet) {
        String session_id = servlet.getHeader(Constants.SESSION_ID);
        LOG.info("【逻辑设备】（获取设备配件类型树） -> 登录令牌：{}", session_id);
        return eamEquPartTypeService.tree(session_id);
    }

    /**
     * 分页获取资产设备配件
     */
    @GetMapping("/logic_equ/parts")
    @ValidLogon
    @ApiOperation(value = "分页获取资产设备配件", response = PageAssetEquPartRsp.class)
    @ApiImplicitParam(name = "session_id", value = "访问令牌", required = true, dataType = "string", paramType = "header")
    public Object pageEquPart(HttpServletRequest servlet,
                              @Valid @ModelAttribute PageAssetEquPartReq request, BindingResult valid) {
        request.setSession_id(servlet.getHeader(Constants.SESSION_ID));
        LOG.info("【逻辑设备】（分页获取资产设备配件） -> 请求参数：{}", request);
        if (valid.hasErrors()) {
            throw new BusinessException(valid.getFieldError().getDefaultMessage());
        }
        SearchEamEquPartReq search = new SearchEamEquPartReq();
        BeanUtils.copyProperties(request, search);
        search.setSelect_type(request.getField_type());
        search.setSelect_value(request.getField_value());
        return eamEquPartInfoService.search(search);
    }

    /**
     * 获取企业通用设备属性
     */
    @GetMapping("/logic_equ/attr/common")
    @ValidLogon
    @ApiOperation(value = "获取通用设备属性", response = EquCommonAttr[].class)
    @ApiImplicitParam(name = "session_id", value = "访问令牌", required = true, dataType = "string", paramType = "header")
    public Object getCommonAttr(HttpServletRequest servlet,
                                @Valid @RequestBody GetCommonAttrReq request, BindingResult valid) {
        String sessionId = servlet.getHeader(Constants.SESSION_ID);
        request.setSession_id(sessionId);
        LOG.info("【逻辑设备】（获取通用设备属性） -> 请求参数：{}", request);
        if (valid.hasErrors()) {
            throw new BusinessException(valid.getFieldError().getDefaultMessage());
        }
        return eamEquInfoService.getCommonAttr(request);
    }

    /**
     * 获取企业自定义设备属性
     */
    @GetMapping("/logic_equ/attr/diy")
    @ValidLogon
    @ApiOperation(value = "获取自定义设备属性", response = EquDiyAttr[].class)
    @ApiImplicitParam(name = "session_id", value = "访问令牌", required = true, dataType = "string", paramType = "header")
    public Object getEquDiyAttr(HttpServletRequest servlet,
                                @Valid @RequestBody GetDiyAttrReq request, BindingResult valid) {
        String sessionId = servlet.getHeader(Constants.SESSION_ID);
        request.setSession_id(sessionId);
        LOG.info("【逻辑设备】（获取自定义设备属性） -> 请求参数：{}", request);
        if (valid.hasErrors()) {
            throw new BusinessException(valid.getFieldError().getDefaultMessage());
        }
        return eamEquInfoService.getDiyAttr(request);
    }

    /**
     * 新增
     */
    @PostMapping("/logic_equ")
    @ValidLogon
    @ApiOperation(value = "新增")
    @ApiImplicitParam(name = "session_id", value = "访问令牌", required = true, dataType = "string", paramType = "header")
    public void add(HttpServletRequest servlet,
                    @Valid @RequestBody AddLogicEquReq request, BindingResult valid) {
        String staffId = UserDataUtil.getStaffId(servlet);
        String enterpriseId = UserDataUtil.getUserSelectedEnterpriseId(servlet);
        request.setCreator_id(staffId);
        request.setEnterprise_id(enterpriseId);
        request.setSession_id(servlet.getHeader(Constants.SESSION_ID));
        LOG.info("【逻辑设备】（新增） -> 请求参数：{}", request);
        if (valid.hasErrors()) {
            throw new BusinessException(valid.getFieldError().getDefaultMessage());
        }
        osmLogicEquService.add(request);
    }

    /**
     * 更新
     */
    @PutMapping("/logic_equ")
    @ValidLogon
    @ApiOperation(value = "更新")
    @ApiImplicitParam(name = "session_id", value = "访问令牌", required = true, dataType = "string", paramType = "header")
    public void update(HttpServletRequest servlet, @Valid @RequestBody UpdateLogicEquReq request, BindingResult valid) {
        request.setEnterprise_id(UserDataUtil.getUserSelectedEnterpriseId(servlet));
        request.setSession_id(servlet.getHeader(Constants.SESSION_ID));
        LOG.info("【逻辑设备】（更新） -> 请求参数：{}", request);
        if (valid.hasErrors()) {
            throw new BusinessException(valid.getFieldError().getDefaultMessage());
        }
        osmLogicEquService.update(request);
    }

    /**
     * 分页查询资产设备信息
     */
    @GetMapping("/logic_equ/asset_equs")
    @ValidLogon
    @ApiOperation(value = "分页查询资产设备信息", response = PageAssetEquRsp.class)
    @ApiImplicitParam(name = "session_id", value = "访问令牌", required = true, dataType = "string", paramType = "header")
    public Object getAssetEquPage(HttpServletRequest servlet,
                                  @Valid @ModelAttribute PageAssetEquReq request, BindingResult valid) {
        request.setSession_id(servlet.getHeader(Constants.SESSION_ID));
        if (null == request.getBelong_type()
                || OsmLogicEqu.BelongType.SELF == request.getBelong_type()) {
            request.setBelonger_id(UserDataUtil.getUserSelectedEnterpriseId(servlet));
        }
        LOG.info("【资产设备】（分页查询设备信息） -> 请求参数：{}", request);
        if (valid.hasErrors()) {
            throw new BusinessException(valid.getFieldError().getDefaultMessage());
        }
        return eamAssetEquService.page(request);
    }

    /**
     * 查询资产设备详情
     */
    @GetMapping("/logic_equ/asset_equ/{id}")
    @ValidLogon
    @ApiOperation(value = "查询资产设备详情", response = AssetEquDetail.class)
    @ApiImplicitParam(name = "session_id", value = "访问令牌", required = true, dataType = "string", paramType = "header")
    public Object detail(HttpServletRequest servlet,
                         @ApiParam(name = "id", value = "设备Id", required = true) @PathVariable String id) {
        GetAssetEquDetailReq request = new GetAssetEquDetailReq();
        request.setId(id);
        request.setSession_id(servlet.getHeader(Constants.SESSION_ID));
        LOG.info("【资产设备】（查询设备详情） -> 请求参数：{}", request);
        return eamAssetEquService.detail(request);
    }

    /**
     * 查询资产设备详情
     */
    @GetMapping("/logic_equ/customer/search")
    @ValidLogon
    @ApiOperation(value = "查询客户信息", response = SearchCustomerRsp.class)
    @ApiImplicitParam(name = "session_id", value = "访问令牌", required = true, dataType = "string", paramType = "header")
    public Object searchCustomer(HttpServletRequest servlet,
                                 @ApiParam(name = "customer_name", value = "客户名称")
                                 @RequestParam(required = false) String customer_name) {
        SearchCustomerReq request = new SearchCustomerReq();
        request.setCustomer_name(customer_name);
        request.setCompany_id(UserDataUtil.getUserSelectedEnterpriseId(servlet));
        LOG.info("【资产设备】（查询设备详情） -> 请求参数：{}", request);
        return eamAssetEquService.searchCustomer(request);
    }

    /**
     * 获取计量单位列表
     */
    @GetMapping("/logic_equ/measure_units")
    @ValidLogon
    @ApiOperation(value = "获取计量单位列表", response = MeasureUnit[].class)
    @ApiImplicitParam(name = "session_id", value = "访问令牌", required = true, dataType = "string", paramType = "header")
    public Object getMeasureUnitList(HttpServletRequest servlet) {
        String session_id = servlet.getHeader(Constants.SESSION_ID);
        LOG.info("【逻辑设备】（获取计量单位列表） -> 登录令牌：{}", session_id);
        return eamMeasureUnitService.getBySessionId(session_id);
    }

    /**
     * 获取供应商列表
     */
    @GetMapping("/logic_equ/supplier")
    @ValidLogon
    @ApiOperation(value = "获取供应商列表", response = Supplier[].class)
    @ApiImplicitParam(name = "session_id", value = "访问令牌", required = true, dataType = "string", paramType = "header")
    public Object getSupplierList(HttpServletRequest servlet) {
        String session_id = servlet.getHeader(Constants.SESSION_ID);
        LOG.info("【逻辑设备】（获取供应商列表） -> 登录令牌：{}", session_id);
        return eamSupplierService.getBySessionId(session_id);
    }

    /**
     * 获取生产厂家列表
     */
    @GetMapping("/logic_equ/manufactors")
    @ValidLogon
    @ApiOperation(value = "生产厂家列表", response = Manufactor[].class)
    @ApiImplicitParam(name = "session_id", value = "访问令牌", required = true, dataType = "string", paramType = "header")
    public Object getManufactorList(HttpServletRequest servlet) {
        String session_id = servlet.getHeader(Constants.SESSION_ID);
        LOG.info("【逻辑设备】（生产厂家列表） -> 登录令牌：{}", session_id);
        return eamManufactorService.getBySessionId(session_id);
    }

    /**
     * 获取项目列表
     */
    @GetMapping("/logic_equ/projects")
    @ValidLogon
    @ApiOperation(value = "获取项目列表", response = ProjectRow[].class)
    @ApiImplicitParam(name = "session_id", value = "访问令牌", required = true, dataType = "string", paramType = "header")
    public Object getProjectList(HttpServletRequest servlet) {
        String session_id = servlet.getHeader(Constants.SESSION_ID);
        ProjectPageReq req = new ProjectPageReq();
        req.setPage_num(1);
        req.setPage_size(1000);
        req.setSession_id(session_id);
        LOG.info("【逻辑设备】（获取项目列表） -> 登录令牌：{}", session_id);
        ProjectPageRsp rsp = eamProjectService.page(req);
        if (null != rsp) {
            return rsp.getData_list();
        } else {
            return null;
        }
    }
}
